package nl.sogyo.objectvisualisatie.data;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

/**
 * A SourceCode object contains all sourcecode of one class
 * each line will be saved in a different record of an
 * ArrayList
 * @author Ben
 *
 */

public class SourceCode{
	
	private ArrayList<String> code;	// ArrayList with the sourcecode of a file
	
	/**
	 * Constructor in which a file will be loaded in a BufferdReader, who
	 * will read out each line of source code
	 * @param sourcepath = path (dir) in which the sourcefile is saved
	 * @param fileName	 = fileName (.class) that will be read
	 */
	public SourceCode(String sourcepath, String fileName) 
	{ 
		code = new ArrayList<String>(); 
		   
		String line = null; 
		BufferedReader in = null; 
		 
		try { 
			in = new BufferedReader(new FileReader(sourcepath+fileName)); 
			while ((line = in.readLine()) != null) 
			code.add(line);
		} 
		catch (IOException ex) { 
			System.err.println("Problem reading " + fileName); 
		}  
		finally { 
			try { 
				if (in != null) 
					in.close(); 
				} 
			catch (IOException e) {} 
			} 
	}
	
	/**
	 * Return a current linenumber of this classfile
	 * @param lineNum = linenumber of the line that will be returned
	 * @return		  = String sourceline which has lineNum number
	 */
	public String showLine(int lineNum) 
	{ 
		if (code == null)
			return "No code to show"; 
	 
		if ((lineNum < 1) || (lineNum > code.size())) 
			return "Line no. out of range"; 
	 
		return ( "" + lineNum + " || " + code.get(lineNum-1)); // use num-1  
	}
	
	/**
	 * Get the whole sourcefile
	 * @return = all source code of this file
	 */
	public ArrayList<String> showAll() 
	{ 
		return code;
	}
}
